# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 14:55:43 2013

@author: aponteeduarddo@gmail.com
Copyright Eduardo Aponte 2013.
"""

from mex_binder import binder_py

mx_eyelink_set_tracker_node = binder_py('mx_eyelink_set_tracker_node')
mx_eyelink_set_tracker_node.mx_c.headers = ['<eyelink.h>','"mex.h"']
mx_eyelink_set_tracker_node.mx_c.code = '''

void _main( ELINKADDR node )
{
    eyelink_set_tracker_node( node ); 
    return;
}


void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    int i;
    /* Buffer size */
    int bs; 
    /* Matlab buffer: WARNING no protection against buffer over load */
    char *mb;
    /* Eyelink char. To support compatibility.*/
    ELINKADDR elb;
    
    
    /* Verify input arguments. */
    if(nrhs != 1 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs != 0 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
    
    
    if ( mxIsChar(*prhs) != 1 )
      mexErrMsgTxt( "node must be a string.");
      
    mb  = mxArrayToString(*prhs);
    
    if(mb == NULL) 
      mexErrMsgTxt("Could not convert input to string.");
    
    bs  = (mxGetM(*prhs) * mxGetN(*prhs));

    if(bs != ELINKADDRSIZE)
        mexErrMsgTxt("node should be exactly 16 characters.");
        
    for (i = 0; i < ELINKADDRSIZE; i++)
        elb[i] = (byte ) mb[i];
      
    _main( elb );
    
    return;
    
}


'''

mx_eyelink_set_tracker_node.mx_c.mdoc = \
'''function [ status ] = mx_eyelink_set_tracker_node( node )
%MX_EYELINK_SET_TRACKER_NODE
%
% Address used for non-connected time requests and message sends. the 
% "proper" way to do this is with the "node" type of functions but we allow a 
% "back door" to simplify higher level support functions. This is also the 
% address used under Windows for looking for tracker (an IP broadcast is used 
% on all other platforms). There is a bug in the Windows networking, causing 
% broadcasts sent on all cards to have the IP source addres of only the first 
% card. This means the tracker sends its connection reply to the wrong address. 
% So the exact address or a subnet broadcast address (i.e. 100.1.1.255 for a 
% subnet mask of 255.255.255.0) needs to be set to that of the tracker.
%
% Parameters:
% node is a string of 16 characters.
%   
'''
mx_eyelink_set_tracker_node.write_c()
mx_eyelink_set_tracker_node.write_m()
mx_eyelink_set_tracker_node.compile()
mx_eyelink_set_tracker_node.write_sh()

